#!/usr/bin/env python
#-*- encoding:utf-8 -*-
#
#       Config
#
#       Kévin Gomez <geek63@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

from ConfigParser import SafeConfigParser as ConfigParser
import sys, os

from libs.Singleton import Singleton


ICONS_DIR = './gui/icons'
USER_CONFIG_FILE = '~/.update_checker.conf'


class Config(Singleton):

    def __init__(self, file):
        self.conf = {}
        self.conf_file = file

        self.getConf()

    def getConf(self, force=True):

        if self.conf and not force:
            return

        try:
            self.parser = ConfigParser()
            self.parser.read(os.path.expanduser(self.conf_file))
        except Exception, err:
            print '[!] Malformation dans le fichier de configuration détectée'
            print '-'*10+'\n'+str(err)+'\n'+'-'*10
            sys.exit(1)

        try:
            for var in self.parser.options('general'):
                try:
                    self.conf[var] = int(self.getInt(var))
                except ValueError:
                    self.conf[var] = unicode(self.get(var))
        except Exception, e:
            print '[!] Erreur détectée dans le fichier de configuration'
            print e
            sys.exit(1)

    def get(self, var):

        return self.parser.get('general', var)

    def getInt(self, var):

        return self.parser.getint('general', var)

    def getBool(self, var):

        return self.parser.getboolean('general', var)

    def set(self, var, value):

        return self.parser.set('general', var, unicode(value))

    def save(self):
        self.parser.write(open(os.path.expanduser(self.conf_file), 'w'))
